<!-- 
  期望的数据格式如下
    [
      {
        groupName: 'A',
        groupList: [
          {
            ...
            name:"鞍山"
          },
          {
            ...
            name:"安庆"
          }
        ]
      },
      {
        groupName: 'B',
        groupList: [
          {
            ...
            name:"北京"
          },
          {
            ...
            name:"保定"
          }
        ]
      }
    ]
 -->

<template>
  <div class="page-city">
    <!-- 分组列表数据 -->
    <div class="list">
      <div
        class="item"
        :class="[group.groupName]"
        v-for="group in cityGroup"
        :key="group.groupName"
      >
        <div class="item-group">{{ group.groupName }}</div>
        <ul>
          <li v-for="city in group.groupList" :key="city.cityId">
            {{ city.name }}
          </li>
        </ul>
      </div>
    </div>

    <!-- 快速选择 -->
    <div class="ks-list">
      <div
        class="ks-list__item"
        :class="{ active: activeName === item }"
        v-for="item in qsList"
        :key="item"
        @click="handleClick(item)"
      >
        {{ item }}
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from "vue";
import axios from "axios";

interface ICity {
  cityId: number;
  isHot: 0 | 1;
  name: string;
  pinyin: string;
}

interface IGroup {
  groupName: string;
  groupList: ICity[];
}

interface IOffset {
  name: string;
  top: number;
}

const cities = ref<ICity[]>([]);
// 分组元素距离顶部距离的一个集合 [{name: 'A', top: 0}, {name: 'B', top: 252}]
const cityGroupOffsetTop: IOffset[] = [];

const cityGroup = computed(() => {
  let result: IGroup[] = [];

  cities.value.forEach((city) => {
    // 1. 取出当前城市的拼音首字母
    const name = city.pinyin.substring(0, 1).toUpperCase();
    // 2. 判断当前 name 是否在 result 结果中已经存在了
    const index = result.findIndex((group) => group.groupName === name);
    if (index === -1) {
      // 不存在，将当前 city 组装成相应格式，追加到 result 中
      result.push({
        groupName: name,
        groupList: [city],
      });
    } else {
      // 存在，将当前 city 追加到 result 中对应分组中的 groupList 里面去。
      result[index].groupList.push(city);
    }
  });

  // 做一个排序之后返回
  return result.sort((a, b) => {
    return a.groupName.charCodeAt(0) - b.groupName.charCodeAt(0);
  });
});
// 当前高亮显示的分组名
const activeName = ref("A");
const qsList = computed(() => {
  return cityGroup.value.map((group) => group.groupName);
});

/**
 * 右侧快速选择点击
 */
const handleClick = (item: string) => {
  // 1. 获取点击的元素距离顶部的距离
  let offsetTop = (document.querySelector(`.${item}`) as HTMLDivElement)
    .offsetTop;

  // 2. 直接操作 scrollTop 距离顶部的距离
  // document.documentElement.scrollTop = offsetTop;
  document.documentElement.scrollTo({
    top: offsetTop,
    behavior: "smooth", // 有动画效果
  });
};

const fetchData = async () => {
  const response = await axios.get("https://m.maizuo.com/gateway?k=180393", {
    headers: {
      "X-Host": "mall.film-ticket.city.list",
    },
  });
  // console.log(response.data.data.cities);
  cities.value = response.data.data.cities;

  nextTick(() => {
    console.log((document.querySelector(".B") as HTMLDivElement).offsetTop);
    // 将 分组的元素 距离顶部的距离给记录下来
    qsList.value.forEach((item) => {
      const top = (document.querySelector(`.${item}`) as HTMLDivElement)
        .offsetTop;

      cityGroupOffsetTop.push({
        name: item,
        top,
      });
    });
  });
};

const getLocation = async () => {
  // 有跨域
  const response = await axios.get(
    "/ws/location/v1/ip?key=RARBZ-ENDW5-DBWIW-QSGIZ-YGYL6-PCFGT"
  );
  // console.log(response);
};

const handleScroll = () => {
  // 1. 当前滚动条距离顶部的距离
  const scrollTop = document.documentElement.scrollTop;
  // console.log(scrollTop);
  // 2. 循环判断当前 scrollTop 属于哪个元素
  for (let i = cityGroupOffsetTop.length - 1; i >= 0; i--) {
    const item = cityGroupOffsetTop[i];

    if (scrollTop >= item.top) {
      // console.log(item.name);

      activeName.value = item.name;
      // 可以不往下遍历了，直接 break
      break;
    }
  }

  // for (let i = 0; i <= cityGroupOffsetTop.length; i++) {
  //   const item = cityGroupOffsetTop[i];

  //   if (scrollTop >= item.top) {
  //     // console.log(item.name);

  //     activeName.value = item.name;
  //     // 可以不往下遍历了，直接 break
  //     break;
  //   }
  // }
};

onMounted(() => {
  fetchData();

  getLocation();

  window.addEventListener("scroll", handleScroll);
});

onUnmounted(() => {
  window.removeEventListener("scroll", handleScroll);
});
</script>

<style lang="scss" scoped>
.item {
  overflow: hidden;
  .item-group {
    padding-left: 5px;
    height: 36px;
    line-height: 36px;
    color: #fff;
    background-color: green;
  }

  li {
    padding-left: 16px;
    height: 36px;
    line-height: 36px;
  }
}

.ks-list {
  position: fixed;
  top: 50%;
  right: 0;
  // 实现一个元素水平垂直居中的方式有哪些？
  transform: translateY(-50%);
  width: 30px;
  background-color: aqua;

  &__item {
    height: 30px;
    line-height: 30px;
    font-size: 16px;
    text-align: center;

    &.active {
      background-color: red;
    }
  }
}
</style>

<!-- RARBZ-ENDW5-DBWIW-QSGIZ-YGYL6-PCFGT -->
